#include <git2.h>
#include <stdio.h>
#include <string.h>

int main() {
	git_libgit2_init();
	char *repo_path = "test_repos";
	git_repository *repo;
	int i;
	int error = git_repository_open(&repo ,repo_path);
	if(error<0) {
		printf("git_repository_open failed, error msg:%s\n", giterr_last()->message);
	}
	printf("open ok\n");

	//head
	git_reference *head;
	git_repository_head(&head, repo);
	//printf("repository head: %s\n", git_reference_name(head));
	if(git_reference_is_branch(head) == 1) {
		//printf("head reference %s is branch\n", git_reference_name(head));
	} else {
		//printf("head reference %s is'nt branch\n", git_reference_name(head));
	}

	const git_oid *oid = git_reference_target(head);
	char out[GIT_OID_HEXSZ+1];
	git_oid_fmt(out, oid);
	//printf("head reference target oid:%s\n", out);

	git_commit *commit;
	error = git_commit_lookup(&commit, repo, oid);
	if(error !=0) {
		printf("git_commit_lookup failed, error code:%d, code message:%s\n", error, giterr_last()->message);
		return -1;
	}

	git_tree *tree;
	git_commit_tree(&tree, commit);
	int entry_cnt = git_tree_entrycount(tree);
	//printf("head entry count:%d\n", entry_cnt);

	// const git_tree_entry *e;
	// for(i=0; i<entry_cnt; ++i) {
	// 	e = git_tree_entry_byindex(tree, i);
	// 	bzero(out, GIT_OID_HEXSZ+1);
	// 	git_oid_fmt(out, git_tree_entry_id(e));
	// 	printf("%s,%s,%d\n", git_tree_entry_name(e), out, git_tree_entry_filemode(e));
	// 	git_tree_entry_free(e);
	// };

	//get blob(README.md)
	git_tree_entry *entry;
	error = git_tree_entry_bypath(&entry, tree, "README.md");
	if(error != 0) {
		printf("README.md not exist\n");
		goto cleanup;
	}

	oid = git_tree_entry_id(entry);
	bzero(out, GIT_OID_HEXSZ+1);
	git_oid_fmt(out, oid);
	printf("%s,%s,%d\n", git_tree_entry_name(entry), out, git_tree_entry_filemode(entry));
	git_tree_entry_free(entry);

	git_blob *blob;
	error = git_blob_lookup(&blob, repo, oid);
	if(error !=0) {
		printf("%s not found\n", out);
		goto cleanup;
	}

	if(git_blob_is_binary(blob) == 1) {
		printf("%s is binary\n", out);
	} else {
		printf("%s is text\n", out);
	}
	printf("%s size:%lld\n", out, git_blob_rawsize(blob));
	//printf("%s content:%s\n", out, git_blob_rawcontent(blob));
	git_blob_free(blob);

	// git_object *object;
	// bzero(out, GIT_OID_HEXSZ+1);
	// git_oid_fmt(out, oid);
	// error = git_object_lookup(&object, repo, oid, GIT_OBJ_ANY);
	// if(error != 0) {
	// 	printf("%s not found\n", out);
	// 	goto cleanup;
	// }
	// if(git_object_type(object) != GIT_OBJ_BLOB) {
	// 	printf("%s type error\n", out);
	// 	goto cleanup;
	// }
	// printf("%s size:%lld\n", out, git_blob_rawsize((git_blob*)object));
	// // printf("%s content:%s\n", out, git_blob_rawcontent((git_blob*)object));
	// git_object_free(object);

	//上述注释代码有问题，随机性出现not found

	cleanup:
		git_tree_free(tree);
		git_commit_free(commit);
		git_reference_free(head);
		git_repository_free(repo);
	return 0;
}
